import { defineStore } from 'pinia'
import { ref } from 'vue'
import { 
  getRoles, 
  getRoleDetail, 
  createRole, 
  updateRole, 
  deleteRole,
  getRolePermissions,
  updateRolePermissions
} from '@/request/user-role-api'
import type { Role, PageQueryParams, RoleCreateRequest, RoleUpdateRequest } from '@/model/user-role-model'

/**
 * 角色管理模块的Store
 */
export const useRoleStore = defineStore('role', () => {
  // 角色列表
  const roleList = ref<Role[]>([])
  // 角色总数
  const roleTotal = ref(0)
  // 当前角色
  const currentRole = ref<Role | null>(null)
  // 当前角色的权限ID列表
  const currentRolePermissions = ref<number[]>([])
  // 加载状态
  const loading = ref(false)

  /**
   * 获取角色列表
   * @param params 查询参数
   */
  async function fetchRoleList(params?: PageQueryParams) {
    loading.value = true
    try {
      const res = await getRoles(params)
      if (res.code === 0) {
        // 判断返回的data是数组还是包含roles和total的对象
        if (Array.isArray(res.data)) {
          roleList.value = res.data
          roleTotal.value = res.total || 0
        } else if (res.data && 'roles' in res.data) {
          roleList.value = res.data.roles
          roleTotal.value = res.data.total || 0
        }
      } else {
        console.error('获取角色列表失败:', res.errorMsg)
      }
    } catch (error) {
      console.error('获取角色列表出错:', error)
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取角色详情
   * @param roleId 角色ID
   */
  async function fetchRoleDetail(roleId: number) {
    loading.value = true
    try {
      const res = await getRoleDetail(roleId)
      if (res.code === 0 && res.data) {
        currentRole.value = res.data
      } else {
        console.error('获取角色详情失败:', res.errorMsg)
      }
    } catch (error) {
      console.error('获取角色详情出错:', error)
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取角色的权限
   * @param roleId 角色ID
   */
  async function fetchRolePermissions(roleId: number) {
    loading.value = true
    try {
      const res = await getRolePermissions(roleId)
      if (res.code === 0 && res.data) {
        currentRolePermissions.value = res.data
      } else {
        console.error('获取角色权限失败:', res.errorMsg)
        currentRolePermissions.value = []
      }
    } catch (error) {
      console.error('获取角色权限出错:', error)
      currentRolePermissions.value = []
    } finally {
      loading.value = false
    }
  }

  /**
   * 创建角色
   * @param roleData 角色数据
   */
  async function addRole(roleData: RoleCreateRequest) {
    loading.value = true
    try {
      const res = await createRole(roleData)
      loading.value = false
      return res
    } catch (error) {
      console.error('创建角色出错:', error)
      loading.value = false
      throw error
    }
  }

  /**
   * 更新角色
   * @param roleId 角色ID
   * @param roleData 角色数据
   */
  async function updateRoleInfo(roleId: number, roleData: RoleUpdateRequest) {
    loading.value = true
    try {
      const res = await updateRole(roleId, roleData)
      loading.value = false
      return res
    } catch (error) {
      console.error('更新角色出错:', error)
      loading.value = false
      throw error
    }
  }

  /**
   * 删除角色
   * @param roleId 角色ID
   */
  async function removeRole(roleId: number) {
    loading.value = true
    try {
      const res = await deleteRole(roleId)
      loading.value = false
      return res
    } catch (error) {
      console.error('删除角色出错:', error)
      loading.value = false
      throw error
    }
  }

  /**
   * 更新角色权限
   * @param roleId 角色ID
   * @param permissionIds 权限ID列表
   */
  async function assignRolePermissions(roleId: number, permissionIds: number[]) {
    loading.value = true
    try {
      const res = await updateRolePermissions(roleId, permissionIds)
      if (res.code === 0) {
        currentRolePermissions.value = permissionIds
      }
      loading.value = false
      return res
    } catch (error) {
      console.error('分配角色权限出错:', error)
      loading.value = false
      throw error
    }
  }

  /**
   * 清空当前角色
   */
  function clearCurrentRole() {
    currentRole.value = null
    currentRolePermissions.value = []
  }

  return {
    roleList,
    roleTotal,
    currentRole,
    currentRolePermissions,
    loading,
    fetchRoleList,
    fetchRoleDetail,
    fetchRolePermissions,
    addRole,
    updateRoleInfo,
    removeRole,
    assignRolePermissions,
    clearCurrentRole
  }
})
